﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Reflection;
using System.Diagnostics;
using NeuroSpeech.XamlExtensions;
using VSLangProj;
using NeuroSpeech.XamlTypeResolver;

namespace XamlTemplateWizard
{
    /// <summary>
    /// Interaction logic for XamlTemplateChooser.xaml
    /// </summary>
    public partial class XamlTemplateChooser : Window
    {
        private IServiceProvider SP;
        public EnvDTE.DTE DTE;

        public XamlTemplateChooser()
        {
            InitializeComponent();

        }


        private T GetOleService<T>()
            where T : class
        {
            T st = SP.GetService(typeof(T)) as T;
            Debug.Assert(st != null, "Could not found " + typeof(T).FullName + " in Ole Service Provider");
            return st;
        }

        /// <summary>
        /// Returns the EnvDTE.ProjectItem object that corresponds to the project item the code 
        /// generator was called on
        /// </summary>
        /// <returns>The EnvDTE.ProjectItem of the project item the code generator was called on</returns>
        protected EnvDTE.ProjectItem GetProjectItem()
        {
            return GetOleService<EnvDTE.ProjectItem>();
        }

        /// <summary>
        /// Returns the EnvDTE.Project object of the project containing the project item the code 
        /// generator was called on
        /// </summary>
        /// <returns>
        /// The EnvDTE.Project object of the project containing the project item the code generator was called on
        /// </returns>
        protected EnvDTE.Project GetProject()
        {
            return GetProjectItem().ContainingProject;
        }



        #region void  XamlTemplateChooser_Loaded(object sender, RoutedEventArgs e)
        void XamlTemplateChooser_Loaded(object sender, RoutedEventArgs e)
        {

            LoadTypes();
        }

        private void LoadTypes()
        {

            try
            {
                Debug.Assert(DTE != null, "DTE Can not be null !!");

                if (SP == null)
                {
                    Microsoft.VisualStudio.OLE.Interop.IServiceProvider oleSP = DTE as Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
                    SP = new Microsoft.VisualStudio.Shell.ServiceProvider(oleSP);
                }

                Array array = DTE.ActiveSolutionProjects as Array;
                EnvDTE.Project p = array.GetValue(0) as EnvDTE.Project;
                VSLangProj.VSProject pr = (VSLangProj.VSProject)p.Object;

                List<Assembly> asmList = LoadAssemblies(pr.References);

                Debug.Assert(asmList.Count > 0, "No references Found !!");

                XTNamespace[] nsList = XTNamespace.Resolve(asmList);

                Debug.Assert(asmList.Count > 0, "No assemblies found !!");

                nsCombo.ItemsSource = nsList;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), ex.Message);
            }
        }
        #endregion

        protected VSProject GetVSProject()
        {
            return (VSProject)GetProject().Object;
        }


        private List<Assembly> LoadAssemblies(VSLangProj.References references)
        {

            List<Assembly> refAssemblies = new List<Assembly>();

            string assemblyName = null;
            string assemblyPath = null;
            foreach (VSLangProj.Reference iref in references)
            {
                if (iref.StrongName)
                {
                    //System.Configuration, Version=2.0.0.0,
                    //Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A
                    assemblyName = iref.Identity +
                        ", Version=" + iref.Version +
                        ", Culture=" + (string.IsNullOrEmpty(iref.Culture) ?
                        "neutral" : iref.Culture) +
                        ", PublicKeyToken=" + iref.PublicKeyToken;
                    try
                    {
                        Assembly a = Assembly.Load(assemblyName);
                        refAssemblies.Add(a);
                    }
                    catch { }
                }
                else
                {
                    assemblyPath = iref.Path;
                    try
                    {
                        Assembly a = Assembly.LoadFrom(assemblyPath);
                        refAssemblies.Add(a);
                    }
                    catch { }
                }
            }

            /*Assembly aex = typeof(XamlCodeContext).Assembly;

            if (!refAssemblies.Any(x => x.FullName == aex.FullName)) {
                refAssemblies.Add(aex);
            }*/

            return refAssemblies;
        }

       



        public Dictionary<string, string> Dictionary { get; set; }

        private void saveButton_Click(object sender, RoutedEventArgs e)
        {



            this.DialogResult = true;
        }


        private void cancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }
    }

}
